package com.ztz.mynewdemo.fragment;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.annotation.Nullable;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.avos.avoscloud.AVAnalytics;
import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.LogInCallback;
import com.ztz.mynewdemo.MainActivity;
import com.ztz.mynewdemo.MyDbHelper;
import com.ztz.mynewdemo.R;
import com.ztz.mynewdemo.utils.AppConfigUtils;
import com.ztz.mynewdemo.utils.AppStringUtils;
import com.ztz.mynewdemo.utils.KeyBoardUtils;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by wqewqe on 2018/1/8.
 */

public class LoginFragment extends Fragment implements DialogInterface.OnKeyListener {
    private static final String TAG = "LoginFragment";
    @BindView(R.id.et_userName)
    EditText etUserName;
    @BindView(R.id.et_pwd)
    EditText etPwd;
    @BindView(R.id.btnLogin)
    Button btnLogin;
    @BindView(R.id.tv_create)
    TextView tvCreate;
    Unbinder unbinder;
    MyDbHelper dbHelper;
    private View mProgressView;
    private View mLoginFormView;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_login, container, false);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        dbHelper = new MyDbHelper(getActivity(), "UserInfoStore.db", null, 2);
        mProgressView = view.findViewById(R.id.login_progress);
        mLoginFormView = view.findViewById(R.id.login_form);
        etPwd.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    attemptLogin();
                    KeyBoardUtils.closeKeyBoard(getActivity(), etPwd);
                    return true;
                }
                return false;
            }
        });
        KeyBoardUtils.openKeyBoard(getActivity(), etUserName);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({R.id.btnLogin, R.id.tv_create})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btnLogin:
                ConnectivityManager connMgr = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo networkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
                Boolean isWifiConn = networkInfo.isConnected();

                //获取移动数据连接的信息
                networkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
                Boolean isMobileConn = networkInfo.isConnected();
                if (isMobileConn || isWifiConn) {
                    attemptLogin();
                } else {
                    Toast.makeText(getActivity(), "请打开网络连接", Toast.LENGTH_SHORT).show();
                }
                KeyBoardUtils.closeKeyBoard(getActivity(), etPwd);
                break;
            case R.id.tv_create:
                FragmentManager manager = getFragmentManager();
                FragmentTransaction transaction = manager.beginTransaction();
                RegisterFragment registerFrag = new RegisterFragment();
                transaction.replace(R.id.rl_content, registerFrag);
                transaction.addToBackStack(null);
                transaction.commit();
                break;
        }
    }

    private void attemptLogin() {
        String userName = etUserName.getText().toString();
        String userPwd = etPwd.getText().toString();
        boolean cancel = false;
        View focusView = null;
        if (!AppStringUtils.checkName(userName)) {
            etUserName.setError("用户名不能为空，并且不能小于3位，大于10位");
            cancel = true;
            focusView = etUserName;
        } else if (!AppStringUtils.checkPassword(userPwd)) {
            etPwd.setError("密码不能为空，并且不能小于4位，大于10位");
            cancel = true;
            focusView = etPwd;
        }
        if (cancel) {
            focusView.requestFocus();
        } else {
            showProgress(true);
//            OkHttpClient client= OkHttpUtils.getOkHttpClient();
//            HttpUrl.Builder builder= HttpUrl.parse(NewsApi.URL.LOGIN).newBuilder();
//            builder.addQueryParameter("username",userName);
//            builder.addQueryParameter("password",userPwd);
//            Request request= RequestUtils.requestGET(builder.build());
//            client.newCall(request).enqueue(new Callback() {
//                @Override
//                public void onFailure(Call call, IOException e) {
//                    e.printStackTrace();
//                }
//
//                @Override
//                public void onResponse(Call call, Response response) throws IOException {
//                    String result=response.body().string();
//                    Log.i(TAG, "onResponse: "+result);
//                    if(response.code()==200)
//                    {
//                        LoginResponse loginResponse=new Gson().fromJson(result,LoginResponse.class);
//                        AppConfigUtils.getInstance().saveLoginInfo(getActivity(),loginResponse);
//                        AppConfigUtils.getInstance().updateLoginInfo(getActivity());
//                        AppConfigUtils.getInstance().setLoginStatu(getActivity(),false);
//                        getActivity().startActivity(new Intent(getActivity(), MainActivity.class));
//                        getActivity().finish();
//                    }
//                }
//            });
            AVUser.logInInBackground(userName, userPwd, new LogInCallback<AVUser>() {
                @Override
                public void done(AVUser avUser, AVException e) {
                    if (e == null) {
                        dialogShow();
//                        getActivity().startActivity(new Intent(getActivity(), MainActivity.class));
//                        AppConfigUtils.getInstance().setLoginStatu(getActivity(),false);
//                        getActivity().finish();
                    } else {
                        showProgress(false);
                        Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }
//        SQLiteDatabase db = dbHelper.getWritableDatabase();
//        Cursor cursor = db.query("UserInfo", new String[]{"password"}, "userName=?", new String[]{userName}, null, null, null);
//        if (cursor.moveToFirst()) {
//            //存在这个用户
//            String pwdTemp = cursor.getString(0);
//            if (pwdTemp.equals(userPwd)) {
//                Toast.makeText(getActivity(), "登录成功", Toast.LENGTH_SHORT).show();
//                Intent intent = new Intent(getActivity(), MainActivity.class);
//                startActivity(intent);
//                getActivity().finish();
//            } else {
//                Toast.makeText(getActivity(), "密码输入不正确,请重新输入", Toast.LENGTH_SHORT).show();
//            }
//        } else {
//            Toast.makeText(getActivity(), "用户不存在,清注册", Toast.LENGTH_SHORT).show();
//        }

    }

    Intent intentDiff = null;

    private void dialogShow() {
        final boolean[] isChecked = {false};
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        View v = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_show, null);
        Dialog dialog = builder.create();
        dialog.setCancelable(false);
        dialog.show();
        dialog.getWindow().setContentView(v);
        RadioGroup rg = (RadioGroup) v.findViewById(R.id.rg);
        Button btn_sure = (Button) v.findViewById(R.id.btn_sure);
        Button btn_cancel = (Button) v.findViewById(R.id.btn_cancel);
        rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                switch (checkedId) {
                    case R.id.rb1:
                        isChecked[0] =true;
                        intentDiff = new Intent(getActivity(), MainActivity.class);
                        intentDiff.putExtra(MainActivity.DESIGN, "design");
                        break;
                    case R.id.rb2:
                        isChecked[0] =true;
                        intentDiff = new Intent(getActivity(), MainActivity.class);
                        intentDiff.putExtra(MainActivity.DESIGN, "news");
                        break;
                    case R.id.rb3:
                        isChecked[0] =true;
                        intentDiff = new Intent(getActivity(), MainActivity.class);
                        intentDiff.putExtra(MainActivity.DESIGN, "history");
                        break;
                    case R.id.rb4:
                        isChecked[0] =true;
                        intentDiff = new Intent(getActivity(), MainActivity.class);
                        intentDiff.putExtra(MainActivity.DESIGN, "jokes");
                        break;
                }
            }
        });
        btn_sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(isChecked[0]){
                    getActivity().startActivity(intentDiff);
                    AppConfigUtils.getInstance().setLoginStatu(getActivity(), false);
                    getActivity().finish();
                }else {
                    Toast.makeText(getActivity(), "请选择你喜欢的页面", Toast.LENGTH_SHORT).show();
                }

            }
        });
        btn_cancel.setOnClickListener(v1 -> {
            dialog.dismiss();
            showProgress(false);
        });
    }

    private void showProgress(final boolean show) {

        int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);

        mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
        mLoginFormView.animate().setDuration(shortAnimTime).alpha(
                show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
            }
        });

        mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
        mProgressView.animate().setDuration(shortAnimTime).alpha(
                show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            }
        });

    }

    @Override
    public void onPause() {
        super.onPause();
        AVAnalytics.onPause(getActivity());
    }

    @Override
    public void onResume() {
        super.onResume();
        AVAnalytics.onResume(getActivity());
    }

    @Override
    public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
        return false;
    }
}
